package handlers

import (
	"ProfessionalCourse5Work/bigsweet/big-sweet-potato-mgr/cache"
	"ProfessionalCourse5Work/bigsweet/big-sweet-potato-mgr/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	context := c.PostForm("context")
	content := c.PostForm("content")
	image := c.PostForm("image")
	if title == "" || context == "" || content == "" || image == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	work := models.Work{
		Title:   title,
		Context: context,
		Content: content,
		Image:   image,
	}
	err := models.DB.Create(&work).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	redis_key := "add_title_" + title
	models.DB.Create(&work)
	marshal, _ := json.Marshal(work)
	cache.Rdb.Set(cache.Ctx, redis_key, marshal, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}

func Del(c *gin.Context) {
	id := c.Query("id")
	err := models.DB.Where("id=?", id).Delete(&models.Work{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "del_id" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}

func List(c *gin.Context) {
	var work []models.Work
	err := models.DB.Find(&work).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	redis_key := "list_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&work)
		jsonData, _ := json.Marshal(work)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &work)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": work,
	})
	return
}
